import { post } from "@/util/request";
import { useStore } from "@/stores";

import {
	deepClone,
	isExpiredFn,
	reduceFn,
	deletingData,
} from "@/static/ts/common";

// 好友搜索
export const FriendInfoSelect = async (data : any) => {
	const obj = await post("/ImApi/FriendInfoSelect", data);
	return obj;
};
// 添加好友
export const FriendApplyAdd = async (data : any) => {
	const obj = await post("/ImApi/FriendApplyAdd", data);
	return obj;
};

// 好友申请列表
export const FriendApply = async () => {
	const obj = await post("/ImApi/FriendApply");
	uni.setStorageSync("FriendApply", obj);
	if (obj.length) {
		uni.setTabBarBadge({
			index: 1,
			text: obj.length.toString(),
		});
	} else {
		uni.removeTabBarBadge({
			index: 1,
		});
	}

	return obj;
};
// 好友申请通过
export const FriendApplyApprove = async (data : any) => {
	const obj = await post("/ImApi/FriendApplyApprove", data);

	return obj;
};
// 通訊錄
export const Friend = async () => {
	const obj = await post("/ImApi/Friend");
	const store = useStore();

	// 获取当前用户信息，用于生成 SessionId
	const myUserInfo = uni.getStorageSync("userInfo");

	// 生成 SessionId 的方法
	const createSessionId = (
		id1 : number | string,
		id2 : number | string
	) : string => {
		const [small, large] = [id1, id2].sort((a, b) => Number(a) - Number(b)); // 排序，确保小的在前
		return `${small}#${large}`;
	};

	// 为每个好友添加 SessionId 和 myUserId
	obj.list.forEach((friend : any) => {
		friend.SessionId = createSessionId(myUserInfo.user_id, friend.user_id);
		friend.myUserId = myUserInfo.user_id;
		friend.id = friend.user_id;
		friend.notes = friend.notes ? friend.notes : "";
	});
	// 将处理后的好友列表保存到数据库
	store.db.saveData("friendList", obj.list);
	obj.originalFriendList = reduceFn(obj.list, "notes", "nick_name");
	uni.setStorageSync("originalFriendList", obj.originalFriendList);
	return obj;
};

// 好友资料更新
export const FriendUpdate = async (data : any) => {
	const obj = await post("/ImApi/FriendUpdate", data);
	Friend();
	return obj;
};
// 好友删除
export const FriendDelete = async (data : any, item : any) => {
	const store = useStore();
	const obj = await post("/ImApi/FriendDelete", data);
	await Friend();
	await deletingData(item);
	await store.db.deleteData("friendList", { id: data.user_id });
	return obj;
};

// 判断并更新好友资料
export const determineFriendUpdate = async (data : any) => {
	const obj = await FriendInfoSelect({ user_id: data.id });
	if (obj.nick_name != data.nick_name || obj.picture != data.picture) {
		await FriendUpdate({
			user_id: data.user_id,
			notes: data.notes || "",
		})

		return obj;
	}
};

// 个人消息发送
export const PersonalSend = async (data : any) => {
	const obj = await post("/ImApi/PersonalSend", data);
	return obj;
};

// 未读消息
export const UnreadMessage = async () => {
	const obj = await post("/ImApi/UnreadMessage");
	const store = useStore();
	let formattedRes = obj.map((e : any) => ({
		...e,
		id: e.Type == 1 ? e.Sender : e.GroupId,
		myUserId: uni.getStorageSync("userInfo").user_id

	}));
	store.db.saveData("unreadMessage", formattedRes);
	return obj;
};
// 消息已读回执
export const MessageReadReceipt = async (data : any) => {
	const obj = await post("/ImApi/MessageReadReceipt", data);
	return obj;
};

// 历史消息
export const HistoryMessage = async (data : any) => {
	const obj = await post("/ImApi/HistoryMessage", data);
	return obj;
};

// 群组创建
export const GroupCreate = async (data : any) => {
	const obj = await post("/ImApi/GroupCreate", data);
	return obj;
};
// 群组详情
export const GroupInfo = async (data : any) => {
	const store = useStore();
	let obj ={}
	try {
		obj = await post("/ImApi/GroupInfo", data);
		
		obj.id = data.group_id;
		let messages = await store.db.loadData("chatList", { chatId: data.group_id });
		if (messages.length) {
			obj = {
				...messages[0],
				...obj,
			};
			store.db.saveData("chatList", [obj]);
		}
		if (obj.member && typeof obj.member == "string") {
			obj.member = JSON.parse(obj.member);
		}
		if (obj.Sender && typeof obj.Sender == "string") {
			obj.Sender = JSON.parse(obj.Sender);
		}
	} catch (error) {
		console.log(error)
		
	}
	
	return obj;
};
// 群组发送消息
export const GroupSend = async (data : any) => {
	const obj = await post("/ImApi/GroupSend", data);
	return obj;
};
// 群组更新
export const GroupUpdate = async (data : any) => {
	const obj = await post("/ImApi/GroupUpdate", data);
	return obj;
};

// 退出群聊
export const GroupExit = async (data : any, item : any) => {
	const store = useStore();
	const obj = await post("/ImApi/GroupExit", data);
	await store.db.deleteData("chatList", { chatId: data.group_id });
	await deletingData(item);

	return obj;
};
// 解散群聊
export const GroupDisband = async (data : any, item : any) => {
	const store = useStore();
	const obj = await post("/ImApi/GroupDisband", data);
	await deletingData(item);
	return obj;
};

// 红包详情
export const RedEnvelopeInFo = async (data : any) => {
	const store = useStore();
	const {
		Content: { redenvelope_id },
	} = data; // 解构获取redenvelope_id
	uni.showLoading()

	const myUserInfo = uni.getStorageSync("userInfo");

	// 获取红包详情
	const obj = await RedEnvelopeInFoFn({ id: redenvelope_id });

	// 判断用户是否已领取红包
	const isUserExist = obj.item.some(
		(item : any) => item.receive.user_id === myUserInfo.user_id
	);
	// 更新红包状态
	if (isUserExist) {
		data.Content.stateType = 1; // 已领取
		data.Content.tips = "该红包已领取";

	} else if (await isExpiredFn(obj.add_time)) {
		data.Content.stateType = 2; // 过期
		data.Content.tips = "该红包已超过24小时，已过期";
	} else if (obj.state) {
		data.Content.stateType = 3; // 已领完
		data.Content.tips = "手慢了，红包派完了";
	} else {
		data.Content.stateType = 0; // 未领取
		data.Content.tips = "";
	}
	data['unread'] = 0

	// 根据红包类型确定存储类型
	const baseDataType = obj.redenvelope_type === 1 ? "singleChat" : "groupChat";
	console.log('根据红包类型确定存储类型', deepClone(data))


	// 保存数据到数据库
	await store.db.saveData(baseDataType, [deepClone(data)]);
	uni.hideLoading()

	return obj; // 返回红包详情
};
export const RedEnvelopeInFoFn = async (data : any) => {
	const obj = await post("/ImApi/RedEnvelopeInFo", data);
	return obj;
};

// 领取红包
export const RedEnvelopeGet = async (data : any) => {
	const obj = await post("/ImApi/RedEnvelopeGet", data);
	return obj;
};